package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRelationService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRelationServiceImpl implements ApUserRelationService {


    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //1：关注  follow  fan
        //1.参数检查
        if(dto.getOperation() == null || dto.getOperation()<0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"作者信息不能为空");
        }

        //根据用户id获取作者昵称
        ApAuthor apAuthor = articleFeign.findByUserId(dto.getAuthorId());
        if(apAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的作者不存在");
        }

        //关注0  ap_user_followr insert
        Integer userId = AppThreadLocalUtils.getUser().getId(); //获取到当前登录的用户id
        if(userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, dto.getAuthorId()));
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, dto.getAuthorId())
                .eq(ApUserFan::getFansId, userId));

        if(dto.getOperation()==0){
            //关注

            if(apUserFollow ==null){
                //insert
                //保存app用户关注信息
                apUserFollow = new ApUserFollow();
                apUserFollow.setUserId(userId);
                apUserFollow.setFollowId(dto.getAuthorId());
                apUserFollow.setFollowName(apAuthor.getName());
                apUserFollow.setCreatedTime(new Date());
                apUserFollow.setIsNotice(true);
                apUserFollow.setLevel((short)1);
                apUserFollowMapper.insert(apUserFollow);
                //fan
                if(apUserFan==null){
                    apUserFan = new ApUserFan();
                    apUserFan.setUserId(dto.getAuthorId());
                    apUserFan.setFansId((long)userId);

                    ApUser apUser = apUserMapper.selectById(userId);
                    if(apUser==null){
                        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
                    }
                    apUserFan.setFansName(apUser.getName());
                    apUserFan.setLevel((short)0);
                    apUserFan.setIsDisplay(true);
                    apUserFan.setIsShieldLetter(false);
                    apUserFan.setIsShieldComment(false);
                    apUserFan.setCreatedTime(new Date());
                    apUserFanMapper.insert(apUserFan);

                    //关注完毕后使用kafka消息同步记录用户关注的行为
                    FollowBehaviorDto dto1 =new FollowBehaviorDto();
                    dto1.setUserId(userId);
                    dto1.setFollowId(dto.getAuthorId());
                    dto1.setArticleId(dto.getArticleId());
                    kafkaTemplate.send("behavior_follow", JSON.toJSONString(dto1));
                }
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户已关注");
            }
        }else{
            //取消关注
            if(apUserFollow!=null){
                apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                        .eq(ApUserFollow::getFollowId, dto.getAuthorId()));
                if(apUserFan !=null){
                    apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, dto.getAuthorId())
                            .eq(ApUserFan::getFansId, userId));
                }else{
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的用户粉丝数据不存在");
                }
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的用户数据不存在");
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
